#!/usr/bin/env python3
"""
依赖更新脚本

使用 pip-tools 编译和更新依赖文件
"""
import subprocess
import sys
from pathlib import Path

def run_command(cmd: list, description: str) -> bool:
    """运行命令并显示结果"""
    print(f"\n🔄 {description}...")
    try:
        result = subprocess.run(cmd, check=True, capture_output=True, text=True)
        print(f"✅ {description} 完成")
        return True
    except subprocess.CalledProcessError as e:
        print(f"❌ {description} 失败:")
        print(e.stdout)
        print(e.stderr)
        return False

def compile_requirements():
    """编译所有依赖文件"""
    requirements_files = [
        ("requirements/base.in", "requirements/base.txt"),
        ("requirements/development.in", "requirements/development.txt"),
        ("requirements/testing.in", "requirements/testing.txt"),
        ("requirements/production.in", "requirements/production.txt")
    ]
    
    all_success = True
    
    for input_file, output_file in requirements_files:
        if not Path(input_file).exists():
            print(f"⚠️ 跳过不存在的文件: {input_file}")
            continue
            
        cmd = [
            "python", "-m", "piptools", "compile",
            "--generate-hashes",
            "--upgrade",
            "--verbose",
            "--output-file", output_file,
            input_file
        ]
        
        if not run_command(cmd, f"编译 {input_file}"):
            all_success = False
    
    return all_success

def sync_requirements():
    """同步当前环境到开发依赖"""
    cmd = [
        "python", "-m", "piptools", "sync",
        "requirements/development.txt"
    ]
    
    return run_command(cmd, "同步开发环境依赖")

def main():
    """主函数"""
    print("📦 开始更新项目依赖...")
    
    # 确保 pip-tools 已安装
    try:
        subprocess.run(["python", "-m", "piptools", "--version"], 
                      check=True, capture_output=True)
    except subprocess.CalledProcessError:
        print("❌ pip-tools 未安装，请先运行: pip install pip-tools")
        sys.exit(1)
    
    # 编译依赖文件
    if not compile_requirements():
        print("❌ 依赖编译失败")
        sys.exit(1)
    
    # 询问是否同步环境
    if input("\n🔄 是否同步当前环境到开发依赖？ (y/N): ").lower() == 'y':
        if not sync_requirements():
            print("❌ 环境同步失败")
            sys.exit(1)
    
    print("\n✅ 依赖更新完成！")
    print("\n📋 建议下一步操作:")
    print("1. 运行安全扫描: python scripts/security-scan.py")
    print("2. 运行测试确保兼容性")
    print("3. 提交更新的依赖文件")

if __name__ == "__main__":
    main()
